﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    /// <summary>
    /// 类和方法都是静态的
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// 字符串转换为数字
        /// </summary>
        /// <param name="value"></param>
        public static int ToInt32(this string? value) 
        {
            if (value == null)
            {
                return 0;
            }
            else 
            {
                return Convert.ToInt32(value);
            }
        }
        /// <summary>
        /// 根据身份证计算出生年月日
        /// </summary>YYYY年mm月dd日
        /// <param name="carId"></param>
        /// <returns></returns>
        public static string GetBithByCardId(this string carId) 
        {
            //130634200411153135
            string result = carId.Substring(6, 8);
            return result;
        }
        /// <summary>
        /// 根据身份证计算出生年月日
        /// </summary>YYYY年mm月dd日
        /// <param name="carId"></param>
        /// <returns></returns>
        public static string FormatDate(this DateTime date)
        {
            return date.ToString("yyyy-MM-dd");
        }


        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(option =>
                {
                    //取出私钥
                    var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                    option.TokenValidationParameters = new TokenValidationParameters()
                    {
                        //验证发布者
                        ValidateIssuer = true,
                        ValidIssuer = builder.Configuration["Authentication:Issuer"],
                        //验证接收者
                        ValidateAudience = true,
                        ValidAudience = builder.Configuration["Authentication:Audience"],
                        //验证是否过期
                        ValidateLifetime = true,
                        //验证私钥
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                    };
                });
        }
    }
}
